﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using RuleCode.Table;

namespace map
{
    public partial class s : System.Web.UI.Page
    {
        protected string user_recid;
        protected string user_id;
        protected double MaxPrice=1000000000;
        protected double MinPrice = 0.0;

        #region 页面载入
        protected void Page_Load(object sender, EventArgs e)
        {
            bool canRead = false;
            if (Request["id"] != null && Request["id"].Trim() != string.Empty)
            {
                user_recid = Request["id"].Trim();
                cbuser user = cbuser.Find("recid="+user_recid );
                if (user.Count > 0)
                {   
                    user_id = user.cbuserid.Value;
                    canRead = true;
                    InitPositionAndIntro(user);
                }
            }

            if (ViewState["Title"] != null)
                this.Title = ViewState["Title"].ToString();
            
            if(!canRead)
            {
                MessageBox.ShowAndRedirect(this.Page, "对不起，您没有权限访问此页面!", ResolveUrl("~/default.aspx"));
                Response.End();
                return;
            }

            if (!IsPostBack)
            {
                InitLoginInfo();
                BindTreeView();
                BindItems(3);
                
            }
            //css动态加载的需要
            BindimageList();
        }
        #endregion

        #region 初始化方法
        protected void BindTreeView()
        {
            this.TreeView1.Nodes.Clear();
            TreeNode rootNode = new TreeNode("所有宝贝","0");  
            this.TreeView1.Nodes.Add(rootNode);
            if (user_recid != null && user_id !=null)
            {
                taobaoItemCat itemcate = taobaoItemCat.Find("taobaouserid='" + user_id + "'", " taobaosort_order desc");                 
                if (itemcate.Count > 0)
                {
                    AddTreeNode(rootNode, "0", itemcate);                       
                }
            }

            //商品页面传递过来选择 商品分类的参数
            if (Session["nodevalue"] != null && Session["nodevalue"].ToString() == "0")
                rootNode.Select();
        }

        protected void AddTreeNode(TreeNode parentNode, string parentcateid,taobaoItemCat itemcate)
        {
            if (parentcateid != string.Empty && parentcateid != null && user_id != null && itemcate.Count >0)
            {
                DataRow[] dRows = itemcate.Select("taobaoparentcid='" + parentcateid + "'", " taobaosort_order desc");
                foreach (DataRow dRow in dRows)
                {
                    TreeNode childNode = new TreeNode(dRow["taobaoname"].ToString(), dRow["taobaocid"].ToString());
                    parentNode.ChildNodes.Add(childNode);
                    AddTreeNode(childNode, dRow["taobaocid"].ToString(), itemcate);

                    //商品页面传递过来选择 商品分类的参数
                    if (Session["nodevalue"] != null && Session["nodevalue"].ToString() == dRow["taobaocid"].ToString())
                        childNode.Select();
                }  
            }
        }

        protected void BindItems(int type)
        {
            if (user_id != null && type>=1 && type<=3)
            {
                string filter = string.Empty;
                if (TextBox_key.Text.Trim() != string.Empty)
                {
                    string searchKey = TextBox_key.Text.Replace(" ", "%");
                    searchKey = "%" + searchKey + "%";
                    filter += "and (taobaotitle like '" + searchKey + "' or taobaodesc like '" + searchKey + "')";
                    double priceFrom = MinPrice ;
                    double priceTo = MaxPrice;
                    try
                    {
                        priceFrom = Convert.ToDouble(TextBox_PriceFrom.Text);
                    }
                    catch { }
                    try
                    {
                        priceTo = Convert.ToDouble(TextBox_PriceTo.Text);
                    }
                    catch { }

                    if (priceTo != MaxPrice || priceFrom != MinPrice)
                    {
                        filter += " and (convert(float , [taobaoprice] ))>= " + priceFrom + " ";
                        filter += " and (convert(float , [taobaoprice] ))< " + priceTo + " ";
                    }
                }

                if (TreeView1.SelectedNode != null  && TreeView1.SelectedNode .Value !="0")
                {
                    string cateFilter = string.Empty;
                    string selectcate = TreeView1.SelectedNode.Value;
                    cateFilter += "   taobaoseller_cids like '%" + selectcate + "%' ";
                    if (TreeView1.SelectedNode.ChildNodes.Count > 0)
                    {
                        foreach (TreeNode treeNode in TreeView1.SelectedNode.ChildNodes)
                        {
                            cateFilter += " or taobaoseller_cids like '%" + treeNode .Value  + "%' ";
                        }
                    }
                    filter += " and ("+cateFilter +")";
                }

                taobaouseritems useritems = taobaouseritems.Find("taobaouserid='" + user_id + "' " + filter);
                //if (useritems.Count > 0)
                {
                    if ((type & 0x1) > 0)
                    {
                        //WebPager1.ControlToPaginate = "DataList1";
                        WebPager1.DataSource = useritems.MyTable;
                        WebPager1.DataBind();
                    }

                    if ((type & 0x2) > 0)
                    {
                        //WebPager2.ControlToPaginate = "DataList2";
                        WebPager2.DataSource = useritems.MyTable;
                        WebPager2.DataBind();
                    }

                    if (Request.Cookies["f980"]!=null && Request.Cookies["f980"]["displaymode"] == "pic")
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "displaymode", "<script type=\"text/javascript\">dispinpic();</script>", false);
                    }
                    else if (Request.Cookies["f980"] != null && Request.Cookies["f980"]["displaymode"] == "list")
                    {

                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "displaymode", "<script type=\"text/javascript\">dispinlist();</script>", false);
                    }
                }
            }
        }

        protected void BindimageList()
        {
            if (user_id != null)
            {
                cbshop shop = cbshop.Find("cbuserid='"+user_id +"'");
                imageList.DataSource = shop.MyTable;
                imageList.DataBind();
                LogoImage.Src = shop.cbpathlogo.Value; 

                IntroLiteral .Text = Server.HtmlDecode(shop.shopgonggao.Value );

                currentShopAnchor.InnerHtml = shop.cbshoptitle.Value;
                this.Title = shop.cbshoptitle.Value  ;
                ViewState["Title"] = this.Title;

                ShopTitleAnchor.InnerHtml = shop.cbshoptitle.Value;
                ShopTitleAnchor.HRef = ResolveUrl("~/s.aspx?id="+user_recid );

                //Css样式和Banner图片
                string cssFileName = (shop.cbshopcssfilename.Value.Trim() == string.Empty) ? "s_i" : shop.cbshopcssfilename.Value;
                if (Request["css"] != null)
                    cssFileName = Request["css"];
                ViewState["css"] = cssFileName;
                RegisterCssFile(cssFileName);

                string shopBannerPic = shop.cbshopbannerpic.Value;
                if (Request["shopbanner"] != null)
                    shopBannerPic = Request["shopbanner"]; 
                if (shopBannerPic.Trim() != string.Empty)
                {
                    ViewState["shopbanner"] = shopBannerPic;
                    BannerDiv.Style["background-image"] ="url("+ shopBannerPic+")";
                }   
            }
        }

        protected void InitPositionAndIntro(cbuser user)
        {
            if (user.Count > 0)
            {
                Label_nick.Text = user.cbusernickname.Value;
                Label_bad.Text = user.pingjia_bad.Value.ToString();
                Label_good.Text = user.pingjia_good.Value.ToString();
                Label_area.Text = user.省编码.Value;
                Literal_chat.Text = cbuser.getChatStrfromuserid(user.cbuserid.Value);
                cbBroker b = cbBroker.Find(" ShopOwnerID = '" + user.cbuserid.Value
                    + "' and StartDate <= '" + DateTime.Today.ToShortDateString() + "'");
                if (b.Count > 0)
                {
                    Literal_jjr.Text = cbuser.getChatStrfromuserid(b.BrokerID.ToString());
                }

                string furl = System.Web.HttpContext.Current.Request.Url.Host;
                if (furl == "www.f980.com" || furl == "f980.com" || furl == "localhost")
                {
                    string ret = RuleCode.Util.getmapurl()+"<div id=\"map_canvas\" style=\"width: 100%; height: 300px\"></div>";
                    PositionLiteral.Text = ret;
                    string ScriptTag = "";
                    ScriptTag =
                        "<script type=\"text/javascript\">initialize(" + user.taobaolong.ToString() + ","
                        + user.taobaolat.ToString() + ");</script>";

                    ClientScript.RegisterStartupScript(GetType(), "bodyevent", ScriptTag);
                }
                else
                {
                    string ret = user.省编码.ToString() + "-"
                        + user.区编码.ToString() + "-"
                        + user.区域编码.ToString() + "-"
                        + user.cbUserBizArea.ToString() + "-"
                        + user.cbaddress.ToString();
                    PositionLiteral.Text = ret;
                }
            }
        }

        /// <summary>
        /// 初始化 登录信息
        /// </summary>
        protected void InitLoginInfo()
        {
            if (this.Request.Url.AbsolutePath != ResolveUrl("~/member/login.aspx")
                    && this.Request.Url.AbsolutePath != ResolveUrl("~/member/regist1.aspx"))
            {
                if (AliApi.appUserId == "")
                {
                    HyperLink_login.Text = "登录";
                    HyperLink_login.NavigateUrl = ResolveUrl("~/member/login.aspx") + "?redirecturl=" + this.Request.Url;

                    HyperLink_logout.NavigateUrl = ResolveUrl("~/member/regist1.aspx") + "?redirecturl=" + this.Request.Url;
                    HyperLink_logout.Text = "注册";
                }
                else
                {
                    HyperLink_login.Text = AliApi.appNickName;
                    HyperLink_login.NavigateUrl = "#";
                    HyperLink_logout.NavigateUrl = ResolveUrl("~/member/loginout.aspx") + "?redirecturl=" + this.Request.Url;
                    HyperLink_logout.Text = "注销";
                }
            }
            else
            {
                HyperLink_login.Text = "登录";
                HyperLink_login.NavigateUrl = ResolveUrl("~/member/login.aspx");

                HyperLink_logout.NavigateUrl = ResolveUrl("~/member/regist1.aspx");
                HyperLink_logout.Text = "注册";
            }
        }
        #endregion
                                                                                                                               
        #region 辅助方法
        #endregion

        #region 事件
        protected void WebPager1_PageIndexChanged(object sender, RuleCode.Controls.PageChangedEventArgs e)
        {
            WebPager1.CurrentPageIndex = e.NewPageIndex;
            BindItems(1);
        }

        protected void WebPager2_PageIndexChanged(object sender, RuleCode.Controls.PageChangedEventArgs e)
        {
            WebPager2.CurrentPageIndex = e.NewPageIndex;
            BindItems(2);
        }

        protected void Button_search_Click(object sender, EventArgs e)
        {
            BindItems(3);
        }

        protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
        {
            BindItems(3);
        }
 
        #endregion

        #region css相关
        protected void RegisterCssFile(string cssFileName)
        {
            HtmlLink cssLink = new HtmlLink();
            cssLink.Attributes["type"] = "text/css";
            cssLink.Attributes["rel"] = "stylesheet";
            cssLink.Attributes["href"] = ResolveUrl("~/css/s_i/" + cssFileName + ".css");
            Page.Header.Controls.Add(cssLink);
        }
        #endregion

    }
}
